package club.web51.classroom_tool.Services;

import club.web51.classroom_tool.DO.sysDO.Msg;
import club.web51.classroom_tool.Enums.MsgEnum;
import club.web51.classroom_tool.Exceptions.ErrDataException;
import club.web51.classroom_tool.Utils.BeanPlusUtils;
import club.web51.classroom_tool.Utils.MsgUtil;
import club.web51.classroom_tool.Utils.ObjectUtil;
import org.springframework.beans.BeanUtils;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Service;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.beans.factory.annotation.Autowired ; 
import club.web51.classroom_tool.Repositories.StudentRepository;
import club.web51.classroom_tool.Utils.SFWhere;
import club.web51.classroom_tool.DO.roleDO.Student;

import java.util.Objects;

/**
 * 服务类
 * @author cxk
 * @since 1.0.0
 */
@Service
public class StudentService {
    @Autowired
    StudentRepository studentRepository;
    /**
     * @param student     实体对象
     * @param pageable 分页对象
     * @return 返回分页\状态码
     */
    public ResponseEntity<Object> search(Student student, Pageable pageable) {
        Page<Student> all = studentRepository.findAll(SFWhere.and(student)
                //.equal(user.getId() > 0, "id", user.getId())
                //.in(true, "userName", longs)
                //.equal(!字段值的判断.equals("") && 字段值的判断 != null, "字段名称", 字段值)
                .like(student.getName() != null, "name", "%" + student.getName() + "%")
                //....
                .build(), pageable);
        return new ResponseEntity<>(all, HttpStatus.OK);
    }

    public Msg updateOne(Student student){
        if(ObjectUtil.isNull(student)){
            throw new ErrDataException(MsgEnum.ERROR_DATA_EMPTY);
        }
        if(Objects.isNull(student.getId())){
            studentRepository.save(student);
            return MsgUtil.success();
        }
        Student student1 = studentRepository.getOne(student.getId());
        BeanPlusUtils.copyPropertiesIgnoreNull(student,student1);

        studentRepository.save(student1);
        return MsgUtil.success();
    }

    public Msg deleteOne(Long id){
        if(ObjectUtil.isNull(id)){
            throw new ErrDataException(MsgEnum.ERROR_DATA_EMPTY);
        }
        studentRepository.deleteById(id);
        return MsgUtil.success();
    }
}
